<?php
/**
+-----------------------------------------------------------------------------------------------
* GouGuOPEN [ 左手研发，右手开源，未来可期！]
+-----------------------------------------------------------------------------------------------
* @Copyright (c) 2021~2024 http://www.gouguoa.com All rights reserved.
+-----------------------------------------------------------------------------------------------
* @Licensed 勾股OA，开源且可免费使用，但并不是自由软件，未经授权许可不能去除勾股OA的相关版权信息
+-----------------------------------------------------------------------------------------------
* @Author 勾股工作室 <hdm58@qq.com>
+-----------------------------------------------------------------------------------------------
*/
namespace app\lawcase\model;

use think\Model;
use think\facade\Db;

class CaseLawyer extends Model
{
    // 设置当前模型对应的数据表名称
    protected $name = 'lawcase_lawyer';
    
    // 设置数据表前缀
    protected $prefix = 'oa_';
    
    // 设置主键
    protected $pk = 'id';
    
    // 设置自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    /**
     * 获取案件律师列表
     * @param array $where 查询条件
     * @param array $param 分页参数
     * @return array
     */
    public function getList($where = [], $param = [])
    {
        $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
        $order = empty($param['order']) ? 'id desc' : $param['order'];
        try {
            $list = $this->where($where)
                ->where('delete_time', 0)
                ->order($order)
                ->paginate(['list_rows' => $rows, 'query' => $param])
                ->each(function($item) {
                    // 获取案件信息
                    $case = Db::name('lawcase')->where('id', $item->case_id)->find();
                    $item->case_code = $case ? $case['case_code'] : '';

                    // 获取律师信息
                    $lawyer = Db::name('admin')->where('id', $item->lawyer_id)->find();
                    $item->lawyer_name = $lawyer ? $lawyer['name'] : '';

                    return $item;
                });
            return $list;
        } catch (\Exception $e) {
            return ['code' => 1, 'data' => [], 'msg' => $e->getMessage()];
        }
    }

    /**
     * 添加案件律师关联
     * @param array $data 关联数据
     * @return int|string新增ID
     */
    public function add($data)
    {
        try {
            $data['create_time'] = time();
            $data['update_time'] = time();
            $id = $this->strict(false)->insertGetId($data);
            add_log('add', $id, $data);

            return $id;
        } catch (\Exception $e) {
            throw new \Exception('添加案件律师关联失败：' . $e->getMessage());
        }
    }

    /**
     * 编辑案件律师关联
     * @param array $data 关联数据
     * @return bool
     */
    public function edit($data)
    {
        try {
            $data['update_time'] = time();
            $res = $this->strict(false)->where('id', $data['id'])->update($data);
            add_log('edit', $data['id'], $data);
            return $res !== false;
        } catch (\Exception $e) {
            throw new \Exception('编辑案件律师关联失败：' . $e->getMessage());
        }
    }

    /**
     * 删除案件律师关联
     * @param int $lawyer_id 律师ID
     * @param int $case_id 案件ID
     * @return bool
     */
    public function remove($lawyer_id, $case_id)
    {
        try {
            $result = $this->where(['lawyer_id' => $lawyer_id, 'case_id' => $case_id])
                ->update(['delete_time' => time()]);
            if($result === false) {
                throw new \Exception('更新delete_time失败');
            }
            add_log('delete', $lawyer_id);
            return true;
        } catch (\Exception $e) {
            throw new \Exception('删除案件律师关联失败：' . $e->getMessage());
        }
    }

    /**
     * 获取案件律师关联详情
     * @param int $id 关联ID
     * @return array|null
     */
    public function getDetail($id)
    {
        $detail = $this->where(['id' => $id, 'delete_time' => 0])->find();
        if (!$detail) {
            return null;
        }

        $detail = $detail->toArray();

        // 获取案件信息
        $case = Db::name('lawcase')->where('id', $detail['case_id'])->find();
        $detail['case_name'] = $case ? $case['name'] : '';
        $detail['case_no'] = $case ? $case['case_no'] : '';

        // 获取律师信息
        $lawyer = Db::name('admin')->where('id', $detail['lawyer_id'])->find();
        $detail['lawyer_name'] = $lawyer ? $lawyer['name'] : '';
        $detail['lawyer_avatar'] = $lawyer ? $lawyer['avatar'] : '';
        $detail['lawyer_mobile'] = $lawyer ? $lawyer['mobile'] : '';

        // 格式化角色类型
        $detail['role_type_text'] = $this->getRoleTypeText($detail['role_type']);

        return $detail;
    }

    /**
     * 批量添加案件律师关联
     * @param int $caseId 案件ID
     * @param array $lawyers 律师数据 [['lawyer_id' => 1, 'role_type' => 1], ...]
     * @return array添加结果，包含成功数量和失败数量
     */
    public function batchAdd($caseId, $lawyers)
    {
        $success = 0;
        $fail = 0;
        $time = time();Db::startTrans();
        try {
            foreach ($lawyers as $lawyer) {
                $data = [
                    'case_id' => $caseId,
                    'lawyer_id' => $lawyer['lawyer_id'],
                    'role_type' => $lawyer['role_type'],
                    'create_time' => $time
                ];
                $id = $this->strict(false)->insertGetId($data);
                if ($id) {
                    $success++;
                    add_log('add', $id, $data);
                } else {
                    $fail++;
                }
            }
            Db::commit();
            return ['success' => $success, 'fail' => $fail];
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception('批量添加案件律师关联失败：' . $e->getMessage());
        }
    }

    /**
     * 获取案件的所有律师
     * @param int $caseId 案件ID
     * @param int $roleType 角色类型，0表示所有类型
     * @return array
     */
    public function getCaseLawyers($caseId, $roleType = 0)
    {
        $query = $this->alias('cl')
            ->join('admin a', 'cl.lawyer_id = a.id')
            ->where(['cl.case_id' => $caseId, 'cl.delete_time' => 0]);
        if ($roleType > 0) {
            $query->where('cl.role_type', $roleType);
        }
        
        return $query->field('cl.*, a.name as lawyer_name, a.avatar, a.mobile, a.email')
            ->select()
            ->each(function($item) {
                $item['role_type_text'] = $this->getRoleTypeText($item['role_type']);return $item;
            })
            ->toArray();
    }

    /**
     * 获取律师参与的所有案件
     * @param int $lawyerId 律师ID
     * @param array $param 查询参数
     * @return array
     */
    public function getLawyerCases($lawyerId, $param = [])
    {
        $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
        $order = empty($param['order']) ? 'lc.id desc' : $param['order'];
        try {
            $list = $this->alias('cl')
                ->join('lawcase lc', 'cl.case_id = lc.id')
                ->where(['cl.lawyer_id' => $lawyerId, 'cl.delete_time' => 0, 'lc.delete_time' => 0])
                ->field('cl.*, lc.name as case_name, lc.case_no, lc.status, lc.accept_date, lc.end_date')
                ->order($order)
                ->paginate(['list_rows' => $rows, 'query' => $param])
                ->each(function($item) {
                    // 格式化角色类型
                    $item->role_type_text = $this->getRoleTypeText($item->role_type);
                    // 格式化案件状态
                    $statusMap = [
                        1 => '进行中',
                        2 => '已结案',
                        3 => '终止'
                    ];
                    $item->status_text = isset($statusMap[$item->status]) ? $statusMap[$item->status] : '未知状态';
                // 格式化日期
                    $item->accept_date_text = date('Y-m-d', strtotime($item->accept_date));
                    $item->end_date_text = $item->end_date ? date('Y-m-d', strtotime($item->end_date)) : '';
                return $item;
                });
            return $list;
        } catch (\Exception $e) {
            return ['code' => 1, 'data' => [], 'msg' => $e->getMessage()];
        }
    }

    /**
     * 检查律师是否已关联到案件
     * @param int $caseId 案件ID
     * @param int $lawyerId 律师ID
     * @return bool
     */
    public function isLawyerInCase($caseId, $lawyerId)
    {
        return $this->where([
            'case_id' => $caseId,
            'lawyer_id' => $lawyerId,
            'delete_time' => 0
        ])->count() > 0;
    }

    /**
     * 更新律师角色类型
     * @param int $id 关联ID
     * @param int $roleType 角色类型
     * @return bool
     */
    public function updateRoleType($id, $roleType)
    {
        try {
            $this->where('id', $id)->update([
                'role_type' => $roleType,
                'update_time' => time()
            ]);
            add_log('edit', $id, ['role_type' => $roleType]);
            return true;
        } catch (\Exception $e) {
            throw new \Exception('更新律师角色类型失败：' . $e->getMessage());
        }
    }

    /**
     * 统计律师案件数量
     * @param int $lawyerId 律师ID
     * @param int $status 案件状态，0表示所有状态
     * @return int
     */
    public function countLawyerCases($lawyerId, $status = 0)
    {
        $query = $this->alias('cl')
            ->join('lawcase lc', 'cl.case_id = lc.id')
            ->where(['cl.lawyer_id' => $lawyerId, 'cl.delete_time' => 0, 'lc.delete_time' => 0]);
        if ($status > 0) {
            $query->where('lc.status', $status);
        }return $query->count();
    }

    /**
     * 获取律师角色类型文本
     * @param int $roleType 角色类型值
     * @return string
     */
    protected function getRoleTypeText($roleType)
    {
        $types = [
            1 => '主办律师',
            2 => '协办律师'
        ];
        return isset($types[$roleType]) ? $types[$roleType] : '未知角色';
    }
}